package com.yc.fruitmarket.controller;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.print.attribute.standard.PDLOverrideSupported;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.yc.fruitmarket.biz.productBiz;
import com.yc.fruitmarket.biz.impl.productBizImpl;


@WebServlet("/productController/*")
public class productController extends BaseServlet {
	private productBiz pb = new productBizImpl();
	
	//获取商品状态
	public void getproductnumL(HttpServletRequest req, HttpServletResponse resp) {
		List<Map<String, String>> list = pb.getproductnumL();
		this.send(resp, list.get(0));
	}
	
	//所有商品名
	public void allpnameL(HttpServletRequest req, HttpServletResponse resp) {
		List<Map<String, String>> list = pb.allpname();
		for(Map<String, String> map : list) {
			map.put("value", map.get("pname"));
		}
		this.send(resp, list);
	}
	
	//下架，上架商品
	public void banL(HttpServletRequest req, HttpServletResponse resp) {
		String pid = req.getParameter("pid");
		String status = req.getParameter("status");
		int Result = pb.banL(pid, status);
		this.send(resp, Result);
	}
	
	//修改商品信息
	public void updateL(HttpServletRequest req, HttpServletResponse resp) {
		try {
			//获取根目录
			String webroot = this.getServletContext().getRealPath("/");
			String fileUploadPath = webroot + "..\\upload";
			File path = new File(fileUploadPath);	//创建文件夹对象
			if(!path.exists()) {					//没有该文件夹就新建
				path.mkdirs();
			}
			
			//开始上传
			//这里用的是原生servlet文件上传方式		smarupload	ajaxfileupload	上传库
			DiskFileItemFactory	factory = new DiskFileItemFactory(1024*1024*10, path);//工厂
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setFileSizeMax(1024*1024*10);								//设置文件存入最大大小
			
			//开始解析参数
			List<FileItem> fileItem = upload.parseRequest(req);		//文件集合
			//除了普通的for循环之外，还可以使用迭代器
			Iterator<FileItem> it = fileItem.iterator();			//开始迭代
			String filePath = "";									//新的路径
			Map<String, String> map = new HashMap();				//创建键值对
			String newFileName = "";
			while(it.hasNext()) {									//迭代循环，有没有下一个
				FileItem fi = it.next();							//下一个
				if(!fi.isFormField()) {	//来判断FileItem对象里面封装的数据是一个普通文本表单字段，还是一个文件表单字段
					//文件说明就是图片				是普通文本表单字段，返回一个true否则返回一个false
					InputStream is = fi.getInputStream();		//输入流
					String name = fi.getName();		//文件图片名字
					String endWith = name.substring(name.lastIndexOf("."));	//后缀
					
					//格式正确，开始写入数据
					newFileName = System.currentTimeMillis() + endWith;//存的文件名称
					filePath = fileUploadPath + "\\" + newFileName;			//文件总的存储路径
					
					//写入
					FileOutputStream fos = new FileOutputStream(new File(filePath));//输出流
					byte[] bs = new byte[1024];
					int length = -1;	//按1024大小存储一次
					while((length = is.read(bs)) != -1) {
						fos.write(bs, 0, length);
					}
					fos.flush();
					is.close();		//关闭输入流
					fos.close();	//关闭输出流
				}else {
					//说明是普通字段		存一下数据，方便后面jdbc操作
					String str = new String(fi.getString().getBytes("ISO-8859-1"), "utf-8");
					map.put(fi.getFieldName(), str);
				}
			}
			//操作数据库
			int result = pb.updateL(map, newFileName);
			this.send(resp, result);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	//添加查询商品信息
	public void bygoods(HttpServletRequest req, HttpServletResponse resp) {
		String pid = req.getParameter("pid");
		String pname = req.getParameter("pname");
		String inventory = req.getParameter("inventory");
		String intprice = req.getParameter("intprice");
		String outprice = req.getParameter("outprice");
		String brand = req.getParameter("brand");
		String tname = req.getParameter("tname");
		String weight = req.getParameter("weight");
		String des = req.getParameter("des");
		String status = req.getParameter("status");
		String currentPage4 = req.getParameter("currentPage4");
		String pagesize = req.getParameter("pagesize");
		List<Map<String, String>> list = pb.bygoods(pid, pname, inventory, intprice, outprice, brand, tname, weight, des, status, currentPage4, pagesize);
		for(Map<String, String> map : list) {
			Pattern pattern = Pattern.compile("^(\\d+)([a-zA-Z]+)$");
	        Matcher matcher = pattern.matcher(map.get("weight"));
	        if (matcher.find()) {  
	        	map.put("weight", matcher.group(1)); 
	        	map.put("weightL", matcher.group(2));
	        }
		}
		this.send(resp, list);
	}
	
	//查询所有的商品
	public void getAllGoods(HttpServletRequest req, HttpServletResponse resp) {
		List<Map<String, String>> list = pb.getAllGoods();
		this.send(resp, list);
	}
	
	//添加商品
	public void add(HttpServletRequest req, HttpServletResponse resp) {
		try {
			//获取根目录
			String webroot = this.getServletContext().getRealPath("/");
			String fileUploadPath = webroot + "..\\upload";
			File path = new File(fileUploadPath);	//创建文件夹对象
			if(!path.exists()) {					//没有该文件夹就新建
				path.mkdirs();
			}
			
			//开始上传
			//这里用的是原生servlet文件上传方式		smarupload	ajaxfileupload	上传库
			DiskFileItemFactory	factory = new DiskFileItemFactory(1024*1024*10, path);//工厂
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setFileSizeMax(1024*1024*10);								//设置文件存入最大大小
			
			//开始解析参数
			List<FileItem> fileItem = upload.parseRequest(req);		//文件集合
			//除了普通的for循环之外，还可以使用迭代器
			Iterator<FileItem> it = fileItem.iterator();			//开始迭代
			String filePath = "";									//新的路径
			Map<String, String> map = new HashMap();				//创建键值对
			String newFileName = "";
			while(it.hasNext()) {									//迭代循环，有没有下一个
				FileItem fi = it.next();							//下一个
				if(!fi.isFormField()) {	//来判断FileItem对象里面封装的数据是一个普通文本表单字段，还是一个文件表单字段
					//文件说明就是图片				是普通文本表单字段，返回一个true否则返回一个false
					InputStream is = fi.getInputStream();		//输入流
					String name = fi.getName();		//文件图片名字
					String endWith = name.substring(name.lastIndexOf("."));	//后缀
					
					//格式正确，开始写入数据
					newFileName = System.currentTimeMillis() + endWith;//存的文件名称
					filePath = fileUploadPath + "\\" + newFileName;			//文件总的存储路径
					
					//写入
					FileOutputStream fos = new FileOutputStream(new File(filePath));//输出流
					byte[] bs = new byte[1024];
					int length = -1;	//按1024大小存储一次
					while((length = is.read(bs)) != -1) {
						fos.write(bs, 0, length);
					}
					fos.flush();
					is.close();		//关闭输入流
					fos.close();	//关闭输出流
				}else {
					//说明是普通字段		存一下数据，方便后面jdbc操作
					String str = new String(fi.getString().getBytes("ISO-8859-1"), "utf-8");
					map.put(fi.getFieldName(), str);
				}
			}
			//操作数据库
			int result = pb.add(map, newFileName);
			this.send(resp, result);
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (FileUploadException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	//条件查询商品
	public void getProduct(HttpServletRequest req, HttpServletResponse resp) {
		String tids = req.getParameter("tid");
		System.out.println("tids1为"+ tids);
		if(tids.equals("")) {
			System.out.println("空");
		}
		String pname = req.getParameter("pname");
		System.out.println("tid有"+tids);
		System.out.println("pname有"+pname);
		int page = Integer.parseInt(req.getParameter("page"));
		int pageSize = Integer.parseInt(req.getParameter("pageSize"));
		int min = "".equals(req.getParameter("min")) ? 0 : Integer.parseInt(req.getParameter("min"));
		int max = "".equals(req.getParameter("max")) ? 0 : Integer.parseInt(req.getParameter("max"));
		//得到商品数量
		int count = pb.getProductCount(max, min, pname, tids);
		System.out.println(count+"数量");
		List<Map<String, String>> list = pb.getProduct(max, min, page, pageSize, pname, tids);
		for(Map<String,String> map: list) {
			map.put("productcount" ,String.valueOf(count));
		}
		this.send(resp, list);
	}
	//页码查询
	public void getGoodsByPage(HttpServletRequest req, HttpServletResponse resp) {
		String tids = req.getParameter("tid");
		System.out.println("tids2为"+ tids);
		String pname = req.getParameter("pname");
		int page = Integer.parseInt(req.getParameter("page"));
		int pageSize = Integer.parseInt(req.getParameter("pageSize"));
		int min = "".equals(req.getParameter("min")) ? 0 : Integer.parseInt(req.getParameter("min"));
		int max = "".equals(req.getParameter("max")) ? 0 : Integer.parseInt(req.getParameter("max"));
		List<Map<String, String>> list = pb.getProduct(max, min, page, pageSize, pname, tids);
		this.send(resp, list);
	}
	//查出具体商品详情
	public void searchProduct(HttpServletRequest req, HttpServletResponse resp) {
		String pid = req.getParameter("pid");
		if("".equals(pid)) {
			return;
		}else {
			List<Map<String, String>> list = pb.searchProduct(pid);
			this.send(resp, list.get(0));
		}
	}
	//查出相关商品
	public void getAboutProduct(HttpServletRequest req, HttpServletResponse resp) {
		String pid = req.getParameter("pid");
		System.out.println(pid+"tid");
		if("".equals(pid) || pid == null) {
			return;
		}
		List<Map<String, String>> list = pb.getAboutProduct(pid);
		if(list.size() > 0) {
			this.send(resp, list);
		}else {
			return;
		}
	}
	//查出最新上架产品
	public void getnewproduct(HttpServletRequest req, HttpServletResponse resp) {
		List<Map<String, String>> list = pb.getnewproduct();
		if(list.size() > 0) {
			this.send(resp, list);
		}else {
			return;
		}
	}
	//查出最畅销的四个产品
	public void getbuyproduct(HttpServletRequest req, HttpServletResponse resp) {
		List<Map<String, String>> list = pb.getbuyproduct();
		if(list.size() > 0) {
			this.send(resp, list);
		}else {
			return;
		}
	}
}
